import {
  getUserInfoApi,
  getRightsApi
} from '@/api/application'
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    //用户信息
    info:{},
    //权限列表信息
    rights:[],
    //是否已经初始化
    initial: false
  },
  mutations: {
    setInfo(state,info){
      state.info = info;
    },
    setRights(state,rights){
      state.rights = rights;
    },
    setToken(state,token){
      setToken(token);
    },
    setInitial(state,flag){
      state.initial = flag;
    }
  },
  getters: {    
  },
  actions: {    
    //初始化
    initial({state,commit}){
      // 获取用户相关信息  
      let  getUserInfo = new Promise((resolve, reject) => {
        try {
          getUserInfoApi().then(data => {
            commit('setInfo', data)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      });
      let getRights = new Promise((resolve,reject)=>{
        try {
          getRightsApi().then(data=>{
            commit("setRights",data)           
            resolve(data)
          }).catch(err=>{
            reject(err)
          })
        }catch(error){
          reject(error)
        }
      })
      return new Promise((resolve,reject)=>{
        getUserInfo.then(userInfo => getRights).then(rights=>{
          commit("setInitial",rights)
          resolve(rights)
        }).catch(error=>reject(error))
      })
    }
  }
}
